package com.jz.yanshe.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.jz.jd.rest.business.RestProxy;
import com.jz.jd.rest.exception.BusinessException;
import com.jz.jd.rest.response.LoginResponse;
import com.jz.jd.rest.response.WXTokenResponse;

import com.jz.yanshe.ui.LoginActivity;
import com.jz.yanshe.util.PreferencesHelper;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import com.jz.yanshe.base.BaseApplication;

/**
 * Created by Administrator on 2018/3/23.
 */

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;

    private String access_token;
    private String openid;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseApplication.api.handleIntent(getIntent(), this);
        initState();
    }

//    @Override
//    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
//
//    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {
        switch (resp.errCode) {

            case BaseResp.ErrCode.ERR_AUTH_DENIED:
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                if (RETURN_MSG_TYPE_SHARE == resp.getType())
                    Toast.makeText(this, "分享失败", Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
                break;
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()) {
                    case RETURN_MSG_TYPE_LOGIN:
                        //拿到了微信返回的code,立马再去请求access_token
                        String code = ((SendAuth.Resp) resp).code;
//                        LogUtils.sf("code = " + code);

                        //就在这个地方，用网络库什么的或者自己封的网络api，发请求去咯，注意是get请求
                        getWXToken(code);
                        break;

                    case RETURN_MSG_TYPE_SHARE:
//                        UIUtils.showToast("微信分享成功");
                        finish();
                        break;
                }
                break;
        }
    }

    private void getWXToken(String code){
        RestProxy.getInstance().getWXToken(BaseApplication.APP_ID_WX, BaseApplication.APP_SECRET, code, new Observer<WXTokenResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(WXTokenResponse wxTokenResponse) {
                openid = wxTokenResponse.openid;
                access_token = wxTokenResponse.access_token;
                wxLogin(wxTokenResponse.access_token,wxTokenResponse.openid);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void wxLogin(final String wx_token, final String wx_app_openid){
        RestProxy.getInstance().wxLogin(wx_token, wx_app_openid, new Observer<LoginResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(LoginResponse loginResponse) {
                if(loginResponse.list.get(0).user_token!=null && !loginResponse.list.get(0).user_token.equals("")){
                    PreferencesHelper.getInstance().set(WXEntryActivity.this,"token",loginResponse.list.get(0).user_token);
//                    startActivity(new Intent(WXEntryActivity.this,HomeActivity.class));
                    finish();
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                if(e instanceof BusinessException){
                    if(((BusinessException)e).errorCode == 3){
                        getWXInfo(wx_token,wx_app_openid);
                    }
                }
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void getWXInfo(String wx_token, String wx_app_openid){
        RestProxy.getInstance().getWXInfo(wx_token, wx_app_openid, new Observer<WXTokenResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(WXTokenResponse wxTokenResponse) {
                Bundle bundle = new Bundle();
                bundle.putString("access_token",access_token);
                bundle.putString("openid",openid);
                bundle.putString("headimgurl",wxTokenResponse.headimgurl);
                bundle.putString("sex",wxTokenResponse.sex);
                bundle.putString("nickname",wxTokenResponse.nickname);
                Intent mIntent = new Intent(WXEntryActivity.this,LoginActivity.class);
                mIntent.putExtras(bundle);
                startActivity(mIntent);
                finish();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void initState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = this.getWindow();
            //取消状态栏透明
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //添加Flag把状态栏设为可绘制模式
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(Color.parseColor("#ffffff"));
            //设置系统状态栏处于可见状态
            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            //让view不根据系统窗口来调整自己的布局
            ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
            View mChildView = mContentView.getChildAt(0);
            if (mChildView != null) {
                ViewCompat.setFitsSystemWindows(mChildView, false);
                ViewCompat.requestApplyInsets(mChildView);
            }
        }
    }
}
